<template>
  <div class="container">
    <!-- 表格 -->
    <el-table class="table"
              :data="foodList"
              border
              style="width: 100%"
              @expand-change="expandClick">
      <el-table-column type="expand">
        <template slot-scope="{ row, $index }">
          <el-form label-position="left"
                   inline
                   class="demo-table-expand">
            <el-row :gutter="0">
              <el-col :span="12">
                <el-form-item label="食品名称"
                              label-width="200px">
                  <span>{{ row.name }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="餐馆名称"
                              label-width="200px">
                  <span>{{ row.restaurant_name }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="0">
              <el-col :span="12">
                <el-form-item label="食品 ID"
                              label-width="200px">
                  <span>{{ row.item_id }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="餐馆 ID"
                              label-width="200px">
                  <span>{{ row.restaurant_id }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="12">
                <el-form-item label="食品介绍"
                              label-width="200px">
                  <span>{{ row.description }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="餐馆地址"
                              label-width="200px">
                  <span>{{ row.restaurant_address }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="12">
                <el-form-item label="食品评分"
                              label-width="200px">
                  <span>{{ row.rating }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="餐馆分类"
                              label-width="200px">
                  <span>{{ row.category }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="12">
                <el-form-item label="月销量"
                              label-width="200px">
                  <span>{{ row.month_sales }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="食品名称"
                       prop="name"
                       align="center">
      </el-table-column>
      <el-table-column label="食品介绍"
                       prop="description"
                       align="center">
      </el-table-column>
      <el-table-column label="评分"
                       prop="rating"
                       align="center">
      </el-table-column>

      <el-table-column prop="prop"
                       label="操作"
                       align="center"
                       width="300">
        <template slot-scope="{ row, $index }">

          <!-- <el-button size="mini"
                     @click="handlerEdit(row)"
                     v-if="$hasBP('btn.Sku.updown')">编辑</el-button>
          <el-button type="danger"
                     size="mini"
                     v-if="$hasBP('btn.Sku.update')">删除</el-button> -->

          <HintButton title="编辑食品信息"
                      size="mini"
                      icon="el-icon-edit"
                      type="primary"
                      v-if="$hasBP('btn.Sku.updown')"
                      @click="handlerEdit (row)"></HintButton>
          <el-popconfirm :title="`你确定删除${row.name}吗?`"
                         @onConfirm="foodList.splice($index,1)">
            <HintButton title="删除食品信息"
                        slot="reference"
                        size="mini"
                        icon="el-icon-delete"
                        type="danger"
                        v-if="$hasBP('btn.Sku.update')"></HintButton>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination class="pagination"
                   background
                   :current-page="page"
                   :page-size="20"
                   layout="total,  prev, pager, next "
                   :total="total"
                   @current-change="handleCurrentChange">
      <!-- @size-change="handleSizeChange" -->
    </el-pagination>
    <!-- 弹出框 -->
    <el-dialog title="修改食品信息"
               :visible.sync="dialogFormVisible"
               :show-close="flag">
      <!-- 弹出框--表单 -->
      <el-form :model="foodForm">
        <el-form-item label="食品名称">
          <el-input v-model="foodForm.name"></el-input>
        </el-form-item>
        <el-form-item label="食品介绍">
          <el-input v-model="foodForm.description"></el-input>
        </el-form-item>
        <el-form-item label="食品分类">
          <el-select v-model="selectedIndex"
                     :placeholder="foodCategory.name">
            <el-option :label="category.name"
                       :value="index"
                       v-for="(category,index) in foodCategory.foods"
                       :key="index"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="食品图片" prop="image_path">
          <el-upload
            size="mini"
            class="avatar-uploader"
             action="/dev-api/v1/addimg/food"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="foodForm.image_path"
              :src="foodForm.image_path"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>

     
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 弹出框--表格 -->
      <el-table style="width: 100%"
                :data="specs">
          <el-table-column prop="specs"
                         label="规格"
                         width="width">
        </el-table-column>
          <el-table-column prop="packing_fee"
                         label="包装费"
                         width="width">
        </el-table-column>
          <el-table-column prop="price"
                         label="价格"
                         width="width">
        </el-table-column>
          <el-table-column prop="prop"
                         label="操作"
                         width="width">
          <template slot-scope="{ row, $index }">
            <el-button type="danger"
                       size="mini"
                       @click="deleteSpecs($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="addBtn">
        <el-button type="primary"
                   @click="dialogFood = true">添加规格</el-button>
      </div>
      <!-- 按钮 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="updateFood">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加规格"
               :visible.sync="dialogFood"
               :show-close="flag">
        <el-form :model="newSpecsObj">
          <el-form-item label="规格"
                      label-width="100px"
                      prop="specs">
            <el-input auto-complete="off"
                    v-model="newSpecsObj.specs"></el-input>
        </el-form-item>
          <el-form-item label="包装费"
                      label-width="100px">
            <el-input-number :min="0"
                           :max="100"
                           v-model="newSpecsObj.packing_fee"></el-input-number>
        </el-form-item>
          <el-form-item label="价格"
                      label-width="100px">
            <el-input-number :min="0"
                           :max="10000"
                           v-model="newSpecsObj.price"></el-input-number>
        </el-form-item>
      </el-form>

      <div slot="footer"
           class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>  
        <el-button type="primary"
                   @click="addSpecs">确 定</el-button>       
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { baseUrl, baseImgPath } from "@/config/env";
import { mapState } from "vuex";
export default {
  name: "foodList",
  data () {
    return {
      baseUrl,
      baseImgPath,
      flag: false,
      restaurant_id: null, //餐馆id
      page: 1,
      restaurant_id: null,
      limit: 20,
      offset: 0,
      total: 1458,
      dialogFormVisible: false,
      dialogFood: false,
      baseUrl: "",
      baseImgPath: "",
      selectedIndex: null,
      // 弹出框表单
      foodForm: {
        name: "",
        item_id: 0,
        category_id: 0,
        new_category_id: 0,
        image_path: "",
        restaurant_id: 0,
        description: "",
        specs: [],
        specfoods: [],
      },
      specs: [{
        specs: "默认",
        packing_fee: 0,
        price: 20,
      }],
      newSpecsObj: {
        specs: '',
        packing_fee: 0,
        price: 20,
      },
    };
  },
  computed: {
    ...mapState({
      foodList: (state) => state.food.foodList || [],
      foodCategory: (state) => state.food.foodCategory || {},
      shopDetail: (state) => state.food.shopDetail,
    }),
  },
  mounted () {
    this.getFoodList();
  },
  methods: {
    // 获取食物列表
    async getFoodList () {
      await this.$store.dispatch("getFoodList", {
        offset: this.offset,
        limit: this.limit,
        restaurant_id: this.restaurant_id,
      });
    },

    // 获取食物种类详情信息
    async getFoodCategory (category_id) {
      // console.log(category_id)
      await this.$store.dispatch("getFoodCategory", category_id);
    },

    //获取店铺详情
    async getShopDetail (restaurant_id) {
      const result = await this.$store.dispatch("getShopDetail", restaurant_id);
    },

    //获取当前页数据
    handleCurrentChange (page) {
      // console.log('val2')
      // console.log(val2)
      this.page = page;
      this.offset = (page * 1 - 1) * this.limit;
      this.getFoodList();
    },

    //点击展开行
    async expandClick (row, expandedRows) {
      if (expandedRows.length > 0) {
        const result = await this.getShopDetail(row.restaurant_id);
        // console.log(this.shopDetail)
        this.$nextTick(() => {
          this.foodList.forEach((item) => {
            // console.log(this.shopDetail.address)
            item.restaurant_address = this.shopDetail.address;
            item.restaurant_name = this.shopDetail.name;
            item.category = this.shopDetail.category;
            item.description = this.shopDetail.description;
          });
        });
        // console.log(this.foodList)
      }
    },

    // 点击编辑,弹出对话框
    handlerEdit (row) {

      this.getFoodCategory(row.category_id)
      this.foodForm.item_id = row.item_id;
      this.foodForm.name = row.name;
      this.foodForm.description = row.description;

      this.foodForm.image_path =row.image_path;

      this.foodForm.category_id = row.category_id;
      this.foodForm.restaurant_id = row.restaurant_id;
      row.specfoods.forEach((item) => this.foodForm.specfoods.push(item));
      this.dialogFormVisible = true;
    },

    // 关闭对话框
    dialogBeforeClose () {
      this.dialogFormVisible = false;
    },

    // 上传图片成功

    handleAvatarSuccess(res, file) {
      // console.log(res)
      this.foodForm.image_path =  "https://elm.cangdu.org/img/"+res.image_path;

    },

    // 上传图片之前
    beforeAvatarUpload (file) {
      // console.log(file)
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 删除规格
    deleteSpecs (index) {
      this.specs.splice(index, 1);
    },

    // 确定添加规格
    addSpecs () {
      this.dialogFood = false;
      this.specs.push(this.newSpecsObj);
    },

    // 取消添加规格
    cancelAdd () {
      this.dialogFood = false;
      this.specfoods = {
        specs: "",
        packing_fee: 0,
        price: 20,
      };
    },

    // 点击确定,编辑食品信息
    async updateFood () {
      const { foodForm, specs } = this;
      foodForm.new_category_id = foodForm.category_id
      foodForm.specs = specs
      try {
        const result = await this.$API.food.reqUpDateFoodDetail(foodForm);
        // console.log(result.status);
        if (result.status == 1) {
          this.$message.success("更新数据成功");
          this.dialogFormVisible = false;
          this.getFoodList();
        } else {
          this.dialogFormVisible = false;
          this.$message.error(result.message);
        }
      } catch (error) {
        this.$message.error(error.message);
      }
    },

    //点击按钮,删除食品信息
    deleteFood (index) {
      //  console.log(index)
      this.foodList.splice(index, 1)
      // this.$message.success("删除成功");
    },
  },
};
</script>

<style lang="less">
.container {
  width: 100%;
  margin-top: 20px;
  .table {
    margin: 20px;
  }
  .pagination {
    margin: 20px;
  }
  .addBtn {
    text-align: center;
    margin-top: 20px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
